package com.common.exception_handler;

import com.base.exception.NormalException;
import com.base.exception.NormalRuntimeException;
import com.base.exception.ValidateException;
import com.base.util.JacksonUtil;
import com.common.util.AjaxMessageUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CommonExceptionHandler extends SimpleMappingExceptionResolver {

    private Logger logger = LoggerFactory.getLogger(CommonExceptionHandler.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, Exception e) {
        String errorMessage=null;
        if(e instanceof NormalException || e instanceof NormalRuntimeException){
            errorMessage=e.getMessage();
        }else if(e instanceof ValidateException){
            ValidateException ex = (ValidateException)e;
            if(ex.getBindingResult() == null){
                errorMessage = ex.getMessage();
            }else{
                BindingResult br = ex.getBindingResult();
                if(br.getErrorCount() > 0){
                    errorMessage = br.getAllErrors().get(0).getDefaultMessage();
                }
            }
        }else{
            logger.error("系统发生错误：{}",e);
            errorMessage = "不好意思，系统内部错误！";
        }
        if(handler instanceof HandlerMethod){
            HandlerMethod m = (HandlerMethod) handler;
            boolean isAjaxHandler=false;
            ResponseBody r = m.getMethod().getDeclaringClass().getAnnotation(ResponseBody.class);
            if(r==null){
                r=m.getMethod().getAnnotation(ResponseBody.class);
            }
            if(r!=null){
                isAjaxHandler=true;
            }else{
                RestController rc = m.getMethod().getDeclaringClass().getAnnotation(RestController.class);
                if(rc!=null){
                    if(m.getMethod().getReturnType()==null||m.getMethod().getReturnType()!= Model.class&&m.getMethod().getReturnType()!= ModelAndView.class){
                        isAjaxHandler=true;
                    }
                }
            }
            if(isAjaxHandler){
                httpServletResponse.setContentType("application/json");
                try {
                    new ObjectMapper().writeValue(httpServletResponse.getOutputStream(),AjaxMessageUtil.createErrorMessage(errorMessage,null));
                } catch (Exception e1) {
                    logger.error("全局异常反回错误信息失败：{}",e);
                }
            }else{
                ModelAndView mav = new ModelAndView();
                mav.setStatus(HttpStatus.INTERNAL_SERVER_ERROR);
                mav.setViewName("error/error");
                return mav;
            }
        }
        return super.resolveException(httpServletRequest,httpServletResponse,handler,e);
    }
}
